<template>
  <div class="w-full max-w-6xl mx-auto flex pt-14 gap-4" :style="{height: 'calc(100vh - 3.5rem)'}">
    <!-- 左侧：提示区 -->
    <aside class="w-80 min-w-[260px] bg-white/95 dark:bg-gray-800/95 rounded-2xl shadow-lg border border-blue-100 dark:border-gray-700 p-4 flex flex-col gap-4 h-full">
      <div>
        <h2 class="text-lg font-bold flex items-center gap-2 mb-2">
          <i class="fa fa-lightbulb-o text-yellow-400"></i>
          提示信息
        </h2>
        <div v-if="hints.length === 0" class="text-gray-400 dark:text-gray-500 text-sm py-6 text-center">
          暂无提示，点击下方按钮获取
        </div>
        <ul v-else class="space-y-2">
          <li v-for="(hint, idx) in hints" :key="idx" class="bg-blue-50 dark:bg-blue-900/30 rounded-lg px-3 py-2 text-gray-700 dark:text-gray-200 text-sm">
            <i class="fa fa-info-circle text-primary mr-1"></i>{{ hint }}
          </li>
        </ul>
      </div>
      <div class="flex flex-col gap-2">
        <button
          class="w-full bg-gradient-to-r from-primary to-secondary text-white font-medium py-2 rounded-xl shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed"
          :disabled="hintCount <= 0"
          @click="getHint"
        >
          获取提示
        </button>
        <div class="text-xs text-gray-500 dark:text-gray-400 text-center">
          剩余提示次数：<span class="font-bold text-primary">{{ hintCount }}</span>
        </div>
      </div>
      <div class="border-t border-gray-200 dark:border-gray-700 pt-4 mt-auto">
        <h3 class="text-base font-semibold mb-2 flex items-center gap-2">
          <i class="fa fa-key text-green-500"></i>
          你的谜底猜测
        </h3>
        <form @submit.prevent="submitGuess" class="flex flex-col gap-2">
          <textarea
            v-model="userGuess"
            rows="2"
            placeholder="请输入你认为的谜底"
            class="w-full rounded-lg border border-gray-200 dark:border-gray-600 focus:outline-none focus:ring-2 focus:ring-primary dark:bg-gray-700 transition-all px-3 py-2 text-sm resize-none"
            :disabled="gameState !== 'playing'"
          ></textarea>
          <button
            type="submit"
            class="bg-gradient-to-r from-green-400 to-green-600 text-white font-medium py-2 rounded-xl shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed"
            :disabled="!userGuess.trim() || gameState !== 'playing'"
          >
            提交谜底
          </button>
        </form>
        <div v-if="guessResult !== null" class="mt-2 text-sm text-center font-medium"
          :class="guessResult ? 'text-green-600 dark:text-green-400' : 'text-red-600 dark:text-red-400'">
          <i class="fa" :class="guessResult ? 'fa-check-circle' : 'fa-times-circle'"></i>
          {{ guessResult ? '恭喜你，猜对了！' : '很遗憾，答案不正确' }}
        </div>
        <button
          class="w-full mt-4 bg-gradient-to-r from-blue-400 to-blue-600 text-white font-medium py-2 rounded-xl shadow-md hover:shadow-lg transition-all"
          @click="showAnswer = true"
        >
          揭晓谜底
        </button>
        <div v-if="showAnswer" class="mt-3 p-3 bg-blue-50 dark:bg-gray-700 rounded-lg border-l-4 border-primary animate-fadeIn">
          <h4 class="font-medium mb-1 flex items-center gap-2">
            <i class="fa fa-lightbulb-o text-yellow-500"></i>
            正确谜底：
          </h4>
          <p class="text-gray-700 dark:text-gray-200 text-sm">{{ currentSoup.base }}</p>
        </div>
      </div>
    </aside>

    <!-- 右侧：主对话区 -->
    <main class="flex-1 flex flex-col h-full relative">
      <!-- 汤面区 -->
      <section class="bg-white/95 dark:bg-gray-800/95 rounded-xl shadow-lg p-4 border border-blue-100 dark:border-gray-700 mb-2">
        <div class="h-1.5 bg-gradient-to-r from-primary to-secondary rounded-full mb-4"></div>
        <h2 class="text-xl font-bold mb-3 flex items-center">
          <i class="fa fa-question-circle text-primary mr-2"></i>
          汤面
        </h2>
        <div class="text-gray-700 dark:text-gray-200 min-h-[100px] leading-relaxed">
          {{ currentSoup.surface }}
        </div>
      </section>

      <!-- 问答历史区 -->
      <section class="bg-white/95 dark:bg-gray-800/95 rounded-xl shadow-md p-4 border border-blue-100 dark:border-gray-700 flex-1 flex flex-col mb-2 min-h-0">
        <div class="h-1.5 bg-gradient-to-r from-secondary to-accent rounded-full mb-4"></div>
        <h2 class="text-xl font-semibold mb-3 flex items-center">
          <i class="fa fa-history text-secondary mr-2"></i>
          问答记录
        </h2>
        <div v-if="questions.length === 0" class="text-gray-500 dark:text-gray-400 text-center py-8 flex flex-col items-center justify-center gap-2">
          <i class="fa fa-commenting-o text-3xl text-blue-200 dark:text-gray-600 float-animation"></i>
          <p>还没有提问，开始你的第一个问题吧！</p>
        </div>
        <div class="question-container space-y-3 max-h-72 overflow-y-auto pr-2 flex-1">
          <div
            v-for="(item, index) in questions"
            :key="index"
            class="p-3 rounded-lg transition-all duration-200 shadow-sm"
            :class="item.isUser
              ? 'bg-blue-50 dark:bg-blue-900/40 border border-blue-100 dark:border-blue-800/50 ml-auto max-w-[85%]'
              : 'bg-gray-50 dark:bg-gray-700/50 border border-gray-100 dark:border-gray-600/50 mr-auto max-w-[85%]'"
          >
            <div class="font-medium flex items-center gap-2">
              <span>{{ item.isUser ? '你' : 'AI' }}</span>
              <span class="text-xs text-gray-500 dark:text-gray-400">
                {{ formatTime(item.timestamp) }}
              </span>
            </div>
            <div class="mt-1 text-gray-700 dark:text-gray-200 text-sm">
              {{ item.text }}
              <!-- AI回答标签 -->
              <span v-if="!item.isUser" class="ml-2 px-2 py-0.5 text-xs rounded-full font-medium"
                :class="getAnswerClass(item.text)">
                {{ item.text }}
              </span>
            </div>
          </div>
        </div>
      </section>

      <!-- 问题输入区 -->
      <section class="bg-white/95 dark:bg-gray-800/95 rounded-xl shadow-lg p-3 border border-blue-100 dark:border-gray-700">
        <form @submit.prevent="submitQuestion" class="flex gap-2">
          <div class="relative flex-1">
            <i class="fa fa-commenting-o absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
            <input
              v-model="newQuestion"
              type="text"
              placeholder="请输入封闭式问题（例：男人是因为口渴吗？）"
              class="w-full py-2.5 rounded-lg border border-gray-200 dark:border-gray-600 focus:outline-none focus:ring-2 focus:ring-primary dark:bg-gray-700 transition-all duration-200 pl-11"
              :disabled="gameState !== 'playing'"
              required
            >
          </div>
          <button
            type="submit"
            class="px-4 py-2.5 bg-gradient-to-r from-primary to-secondary text-white rounded-lg shadow-md hover:shadow-lg transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-1"
            :disabled="!newQuestion.trim() || gameState !== 'playing'"
          >
            <i class="fa fa-paper-plane"></i>
            提问
          </button>
        </form>
        <p class="text-xs text-gray-500 dark:text-gray-400 mt-2 bg-gray-50 dark:bg-gray-700/50 px-3 py-1 rounded-lg inline-block">
          <i class="fa fa-info-circle mr-1 text-primary"></i>
          提示：AI 只会回答 "是"、"否" 或 "无关"
        </p>
      </section>
    </main>
  </div>
  <!-- 固定底部标签 -->

</template>

<script setup>
import { ref, onMounted } from 'vue';

const soups = [
  {
    id: 1,
    surface: "一个男人走进一家酒吧，向酒保要了一杯水。酒保却突然拿出一把枪指着他。男人愣了一下，随后说了声“谢谢”就离开了。为什么？",
    base: "男人打嗝，想通过喝水来缓解。酒保用枪吓他，打嗝立刻好了，所以他道谢离开。",
    hints: [
      "男人并不是因为渴才要水。",
      "酒保的行为其实帮助了男人。",
      "男人有一个小毛病，酒保用特殊方式帮他解决了。"
    ]
  },
  {
    id: 2,
    surface: "一个女人穿着高跟鞋，在沙漠中死了，周围没有任何脚印。她是怎么死的？",
    base: "这个女人是一名宇航员，在沙漠上空执行任务时，航天器失事，她穿着宇航服（带有类似高跟鞋的装备）坠落死亡，所以周围没有脚印。",
    hints: [
      "她不是普通的高跟鞋。",
      "她并不是走到沙漠的。",
      "她的死亡和飞行有关。"
    ]
  },
  {
    id: 3,
    surface: "一个人在雨中行走，没有带任何雨具，头发却一点没湿。为什么？",
    base: "这个人是光头，没有头发，所以头发不会湿。",
    hints: [
      "他没有带伞，但也没有遮挡物。",
      "他的头发和常人不同。",
      "其实他根本没有头发。"
    ]
  }
];

const currentSoup = ref({});
const questions = ref([]);
const newQuestion = ref('');
const hints = ref([]);
const hintCount = ref(3);
const usedHintIdx = ref(0);

const userGuess = ref('');
const guessResult = ref(null); // null/true/false
const showAnswer = ref(false);

const gameState = ref('playing'); // playing, win, lose

const formatTime = (timestamp) => {
  const date = new Date(timestamp);
  return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
};

const getAnswerClass = (answer) => {
  if (answer.includes('是')) return 'bg-green-100 text-green-700 dark:bg-green-900/50 dark:text-green-400';
  if (answer.includes('否')) return 'bg-red-100 text-red-700 dark:bg-red-900/50 dark:text-red-400';
  return 'bg-gray-100 text-gray-700 dark:bg-gray-600/50 dark:text-gray-300';
};

const getHint = () => {
  if (hintCount.value > 0 && usedHintIdx.value < currentSoup.value.hints.length) {
    hints.value.push(currentSoup.value.hints[usedHintIdx.value]);
    usedHintIdx.value++;
    hintCount.value--;
  }
};

const submitQuestion = () => {
  if (!newQuestion.value.trim()) return;
  const userQuestion = {
    text: newQuestion.value,
    isUser: true,
    timestamp: new Date()
  };
  questions.value.push(userQuestion);

  setTimeout(() => {
    const answers = ["是", "否", "无关"];
    // 简单模拟AI回答
    const randomAnswer = answers[Math.floor(Math.random() * answers.length)];
    const aiAnswer = {
      text: randomAnswer,
      isUser: false,
      timestamp: new Date()
    };
    questions.value.push(aiAnswer);
    scrollToBottom();
  }, 800);

  newQuestion.value = '';
  scrollToBottom();
};

const submitGuess = () => {
  // 简单判断：谜底文本包含主要关键词即为正确
  // 去掉正则中的 \-
  const answer = currentSoup.value.base.replace(/[\s，。！？、,.!?]/g, '').toLowerCase();
  const guess = userGuess.value.replace(/[\s，。！？、,.!?]/g, '').toLowerCase();
  // 关键词匹配（可根据实际优化）
  if (answer && guess && answer.includes(guess.slice(0, 6))) {
    guessResult.value = true;
    gameState.value = 'win';
  } else {
    guessResult.value = false;
  }
};

const scrollToBottom = () => {
  setTimeout(() => {
    const container = document.querySelector('.question-container');
    if (container) {
      container.scrollTop = container.scrollHeight;
    }
  }, 100);
};

onMounted(() => {
  currentSoup.value = soups[0];
});
</script>

<style scoped>
@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}
.animate-fadeIn {
  animation: fadeIn 0.3s ease-out forwards;
}
.float-animation {
  animation: float 6s ease-in-out infinite;
}
@keyframes float {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-10px); }
}
/* 滚动条美化 */
.question-container::-webkit-scrollbar {
  width: 5px;
}
.question-container::-webkit-scrollbar-track {
  background: #f1f5f9;
  border-radius: 3px;
}
.question-container::-webkit-scrollbar-thumb {
  background: #c5d1e0;
  border-radius: 3px;
}
.question-container::-webkit-scrollbar-thumb:hover {
  background: #a8b9cc;
}
.dark .question-container::-webkit-scrollbar-track {
  background: #1f2937;
}
.dark .question-container::-webkit-scrollbar-thumb {
  background: #374151;
}
</style>
